﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using DoubleH.Plugins;
using DoubleH.Utility;
using System.Diagnostics;

/* 一次性选择所有的商品性能更高*/
namespace ProductS
{
    /// <summary>
    /// GetProductSWindow.xaml 的交互逻辑
    /// </summary>
    public partial class GetProductS : Window
    {
        public enum EnumProductS
        {
            /// <summary>
            /// 显示ProductS表中所有可采购商品,不包含物料清单
            /// </summary>
            可采购商品,
            /// <summary>
            /// 只显示对应仓库的商品,不包含物料清单
            /// </summary>
            库存调价单商品,
            /// <summary>
            /// 显示所有可销售商品,受负库存销售功能显示(如果不允许则显示所选仓库商品,如果允许则显示ProductS中商品)
            /// </summary>
            可销售商品,
            /// <summary>
            /// 只显示有库存的商品,包含物料清单
            /// </summary>
            调拨单商品,
            /// <summary>
            /// 显示ProductS表中所有可销售商品,包含物料清单
            /// </summary>
            询价单商品
        }

        EnumProductS productType = EnumProductS.可销售商品;
        Table.StoreS storeS= null;
        string firstSearchText = string.Empty;//保存上一个查询的文本,如果当前查询文本包含它,就在 rows 中搜索,不需要再连接数据库,效率更好了.
        double thisWidth = 0, thisHeight = 0;
        Thickness dataGridObjectMargin;
        IEnumerable<Table.ProductS> searchRows = new ObservableCollection<Table.ProductS>();
        ObservableCollection<Table.ProductS> selected = new ObservableCollection<Table.ProductS>();

        ObservableCollection<Table.ProductS> selectedProductS = new ObservableCollection<Table.ProductS>();
        /// <summary>
        /// 获取已选择商品
        /// </summary>
        public ObservableCollection<Table.ProductS> Selected
        {
            get
            {
                return selected;
            }
        }

        bool isMini = false;
        /// <summary>
        /// 是否迷你窗体显示
        /// </summary>
        public bool IsMini
        {
            get { return isMini; }
            set
            {
                isMini = value;
                InitIsMini();
            }
        }

        /// <summary>
        /// 商品选择框
        /// </summary>
        /// <param name="host"></param>
        /// <param name="sales">null 所有商品 true 可销售商品 false 可采购商品</param>
        public GetProductS()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="productType"></param>
        /// <param name="storeSId">获取或设置仓库Id用于显示该仓库的商品列表,-1则表示所有</param>
        public void Init(EnumProductS productType, Table.StoreS storeS)
        {
            this.productType = productType;
            this.storeS = storeS;
            thisWidth = this.Width;
            thisHeight = this.Height;
            dataGridObjectMargin = dataGridObject.Margin;
            this.Title += (" - " + productType.ToString());
            switch (productType)
            {
                case EnumProductS.可销售商品: purchasePrice.Visibility = Visibility.Collapsed; break;
                case EnumProductS.可采购商品: posPrice.Visibility = Visibility.Collapsed; break;
                case EnumProductS.调拨单商品:
                    checkBoxZeroQuantity.IsChecked = true;
                    checkBoxZeroQuantity.IsEnabled = false;
                    quantity.Visibility = Visibility.Collapsed;
                    break;
                default: quantity.Visibility = Visibility.Collapsed; break;
            }
            buttonNew.IsEnabled = Table.UserS.LoginUser.GetAuthority(productType) > Table.UserS.EnumAuthority.查看;

            if (storeS != null )
            {
                checkBoxZeroQuantity.IsChecked = !Table.SysConfig.SysConfigParams.NegativeSales;
                this.Title +=( " ( " + storeS.Name + " )");
            }

            listBox1.ItemsSource = selected;
            listBox1.DisplayMemberPath = "Name";

            textBox1.Focus();

            dataGridObject.ItemsSource = searchRows;

            InitGroup();
            InitEvent();
        }
       
        public void SearchText(string searchText, Int64? groupId)
        {
            bool contectSql = true;
            if (groupId == null && !string.IsNullOrEmpty(firstSearchText) && searchText.Contains(firstSearchText))
                contectSql = false;

            if (contectSql)
            {
                switch (productType)
                {
                    case EnumProductS.可采购商品: searchRows = Table.ProductS.GetList(false, searchText); break;
                    case EnumProductS.可销售商品:
                        if (storeS != null && storeS.Id != -1 && !Table.SysConfig.SysConfigParams.NegativeSales)
                        {
                            searchRows = Table.ProductS.GetListInStoreS(storeS.Id, searchText);
                            if (checkBoxZeroQuantity.IsChecked.Value)
                                searchRows = searchRows.Where(f => f._Quantity > 0);
                        }
                        else
                            searchRows = Table.ProductS.GetList(true, searchText);
                        break;

                    case EnumProductS.库存调价单商品:
                        Debug.Assert(storeS != null);

                        searchRows = Table.ProductS.GetListInStoreS(storeS.Id, searchText);
                            if (checkBoxZeroQuantity.IsChecked.Value)
                                searchRows = searchRows.Where(f => f._Quantity > 0);
                        break;

                    case EnumProductS.调拨单商品:
                        Debug.Assert(storeS != null);
                       
                        searchRows = Table.ProductS.GetListInStoreS(storeS.Id, searchText).Where(f => f._Quantity > 0);       
                        break;
                    case EnumProductS.询价单商品: searchRows = Table.ProductS.GetList(null,null); break;
                }
                if (groupId != null&&searchRows!=null)
                    searchRows = searchRows.Where(f => f.GroupSId==groupId);

            }
            else
                searchRows = from f in searchRows where f.Barcode.Contains(searchText) || f.Code.Contains(searchText) || f.Name.Contains(searchText) select f;

            dataGridObject.ItemsSource = searchRows;
            firstSearchText = searchText;
            if (!isMini)
            {
                textBox1.Clear();
                buttonAll.IsEnabled = dataGridObject.HasItems;
            }
        }

        private void InitEvent()
        {
            buttonAll.Click += (ss, ee) => SelectAllProductS();
            checkBoxZeroQuantity.Click += (ss, ee) => HideProductSWhereQuantityIsZero();
            //通过选择 类别 来搜索商品
            treeView1.MouseLeftButtonUp += (ss, ee) => SearchProductS();
            //回车就搜索商品
            textBox1.KeyDown += (ss, ee) =>
            {
                if (ee.Key == Key.Enter)
                    SearchText(textBox1.Text, null);
            };
            dataGridObject.MouseDoubleClick += (ss, ee) => AddProductInSelectedProductS();
            listBox1.MouseDoubleClick += (ss, ee) => RemoveProductInSelectedProductS();
            buttonNew.Click += (ss, ee) => NewProduct();
            buttonOK.Click += (ss, ee) =>  this.Close(); 
        }

        private void InitIsMini()
        {
            if (isMini)
            {
                this.WindowStyle = WindowStyle.ToolWindow;
                treeView1.Visibility = Visibility.Collapsed;
                label2.Visibility = Visibility.Collapsed;
                treeView1.Visibility = Visibility.Collapsed;
                label1.Visibility = Visibility.Collapsed;
                textBox1.Visibility = Visibility.Collapsed;
                buttonNew.Visibility = Visibility.Collapsed;
                buttonOK.Visibility = Visibility.Collapsed;
                listBox1.Visibility = Visibility.Collapsed;
                checkBoxZeroQuantity.Visibility = Visibility.Collapsed;
                buttonAll.Visibility = Visibility.Collapsed;

                dataGridObject.Margin = new Thickness(0, 0, 0, 0);
                this.Width = 400;
                this.Height = 300;
            }
            else
            {
                this.WindowStyle = WindowStyle.SingleBorderWindow;
                treeView1.Visibility = Visibility.Visible;
                label2.Visibility = Visibility.Visible;
                treeView1.Visibility = Visibility.Visible;
                label1.Visibility = Visibility.Visible;
                textBox1.Visibility = Visibility.Visible;
                buttonNew.Visibility = Visibility.Visible;
                buttonOK.Visibility = Visibility.Visible;
                listBox1.Visibility = Visibility.Visible;

                dataGridObject.Margin = dataGridObjectMargin;
                this.Width = thisWidth;
                this.Height = thisHeight;
            }
        }

        private void InitGroup()
        {
            ObservableCollection<GroupS.GroupSUtility.GroupSBinding> groupBinding = new ObservableCollection<GroupS.GroupSUtility.GroupSBinding>();
            ObservableCollection<Table.GroupS> allGroupS = new ObservableCollection<Table.GroupS>(Table.GroupS.GetList(Table.GroupS.EnumFlag.商品分类, Table.GroupS.EnumEnable.启用));
            foreach (Table.GroupS gs in allGroupS.Where(f => f.ParentId == -1))
            {
                GroupS.GroupSUtility.GroupSBinding gsb = new GroupS.GroupSUtility.GroupSBinding() { Id = gs.Id, Name = gs.Name, ParentId = gs.ParentId, GroupSBindings = new List<GroupS.GroupSUtility.GroupSBinding>() };
                groupBinding.Add(gsb);
                FindGroup(gsb, allGroupS);
            }
            treeView1.ItemsSource = groupBinding;
        }

        private void FindGroup(GroupS.GroupSUtility.GroupSBinding group, ObservableCollection<Table.GroupS> allGroup)
        {
           var gs = allGroup.Where(f => f.ParentId == group.Id);
            if (gs == null)
                return;

            foreach (Table.GroupS g in gs)
            {
                GroupS.GroupSUtility.GroupSBinding gsb = new GroupS.GroupSUtility.GroupSBinding() { Id = g.Id, Name = g.Name, ParentId = g.ParentId, GroupSBindings = new List<GroupS.GroupSUtility.GroupSBinding>() };
                group.GroupSBindings.Add(gsb);

                FindGroup(gsb, allGroup);
            }
        }

        private void HideProductSWhereQuantityIsZero()
        {
            if (treeView1.SelectedItem == null)
                SearchText(string.Empty, null);
            else
                SearchText(string.Empty, ((GroupS.GroupSUtility.GroupSBinding)treeView1.SelectedItem).Id);
        }

        private void SearchProductS()
        {
            if (treeView1.SelectedItem == null)
                return;

            Int64 groupId = ((GroupS.GroupSUtility.GroupSBinding)treeView1.SelectedItem).Id;
            SearchText(string.Empty, groupId);
        }

        private void AddProductInSelectedProductS()
        {
            if (dataGridObject.SelectedItem == null)
                return;

            Table.ProductS p = dataGridObject.SelectedItem as Table.ProductS;
            if (isMini)
            {
                selected.Add(p);
                this.Close();
            }
            else
                AddProductSToSelected(p);
        }

        private void RemoveProductInSelectedProductS()
        {
            if (listBox1.SelectedItem != null)
                selected.Remove((Table.ProductS)listBox1.SelectedItem);
        }

        private void NewProduct()
        {
            MainWindow mw = new MainWindow();
            mw.Init(null);
            mw.ShowDialog();
        }

        private void SelectAllProductS()
        {
            foreach (Table.ProductS obj in dataGridObject.Items)
                AddProductSToSelected(obj);
        }

        private void AddProductSToSelected(Table.ProductS obj)
        {
            if (selected.FirstOrDefault(f => f.Id == obj.Id) == null)
            {
                obj._TempQuantity = -1;
                selected.Add(obj);
            }
        }
    }
}